// pages/search/index.js
Page({
  data:{
    printList:[],
    storageList: []
  },
  onLoad: function (options) {
    var list = wx.getStorageSync('printList');
    if(list.length > 0){
      this.setData({
        storageList: list
      })
    }
    this.start();
  },
  research: function () {
    var _this = this;
    wx.closeBluetoothAdapter({
      complete: function (res) {
        _this.start();
      }
    })
  },
  start: function () {
    if (!wx.openBluetoothAdapter) {
      this.showTip("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。")
      return;
    }
    var _this = this;
    wx.openBluetoothAdapter({
      complete: function (res) {
        _this.getBluetoothAdapterState();
      }
    })
  },
  getBluetoothAdapterState:function(){
    var _this = this;
    wx.getBluetoothAdapterState({
      complete: function (res) {
        if (!!res && res.available) {
          _this.startSearch();
        } else {
          _this.showTip("请开启手机蓝牙")
        }
      }
    })
  },
  startSearch: function () {
    var _this = this;
    wx.showLoading({
      title: '搜索中',
      mask: true
    })
    wx.startBluetoothDevicesDiscovery({
      services: [],
      complete: function (res) {
        setTimeout(function () {
          wx.getBluetoothDevices({
            complete: function (res) {
              wx.hideLoading();
              var list = _this.filterPrint(res.devices);
              _this.setData({
                printList: list
              });
              if(list.length == 0){
                _this.showTip('没有发现新的设备哦');
              }
            }
          });
          wx.stopBluetoothDevicesDiscovery({
            success: function(res) {},
          })
        }, 4000)
      }
    })
  },
  filterPrint:function(list){
    var _this = this;
    let printList = [];
    let storageList = _this.data.storageList;
    for (let i = 0; i < list.length; i++) {
      let base64 = wx.arrayBufferToBase64(list[i].advertisData);
      let str = Array.prototype.map.call(new Uint8Array(list[i].advertisData), x => ('00' + x.toString(16)).slice(-2)).join('');
      if (str.length == 16) {
        let has = false;
        for (let j = 0; j < storageList.length; j++) {
          if (storageList[j].deviceId == list[i].deviceId) {
            has = true; break;
          }
        }
        if (!has) {
          list[i].address = str.toUpperCase()
          printList.push(list[i]);
        }
      }
    }
    return printList;
  },
  connectDevice:function(res){
    var _this = this;
    var index = res.currentTarget.dataset.index;
    var printList = _this.data.printList;
    var deviceId = printList[index].deviceId;
    wx.showLoading({
      title: '连接中...',
      mask: true
    })
    wx.createBLEConnection({
      deviceId: deviceId,
      success(res) {
        var storageList = _this.data.storageList
        storageList.push(printList[index]);
        wx.setStorageSync('printList', storageList);
        _this.closeBLEConnection(deviceId);
        wx.hideLoading();
        wx.navigateBack({});
      },
      fail(res) {
        wx.hideLoading();
        _this.showTip('连接失败');
      }
    })
  },
  closeBLEConnection: function (deviceId){
    wx.closeBLEConnection({
      deviceId: deviceId,
      success: function (res) {
      }
    })
  },
  showTip:function(data){
    wx.showModal({
      content: data,
      showCancel: false
    })
  },
  service:function(){
    this.setData({
      showM: true
    })
  },
  cancelR:function(){
    this.setData({
      showM: false
    })
  },
  confirmR:function(){
    var _this = this;
    wx.setClipboardData({
      data: 'gc13178391565',
      success: function (res) {
        _this.cancelR();
        wx.showToast({
          title: '复制成功',
        })
      }
    })
  }
})